/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Helper;

import java.util.zip.CRC32;

/**
 *
 * @author Administrator
 */
public class CRCControl {

    public static long getCrc32(byte[] data) {

        CRC32 crc32 = new CRC32();
        crc32.update(data);
        return crc32.getValue();
    }

    public static byte[] getCrc16(byte[] src,int len) {

       short CRC = (short) 0xffff;
        byte Tmp;

        for (int i = 0; i < len; i++) {
            CRC ^= (src[i] & 0xff);
            for (int j = 0; j < 8; j++) {
                Tmp = (byte) (CRC & 0x01);
                CRC = (short) ((CRC & 0xffff) >>> 1);
                if (Tmp != 0) {
                    CRC ^= 0xA001;
                }
            }
        }
        byte [] CrcCode = new byte[2];
        CrcCode = typeConvert.short2byte(CRC);
        return CrcCode;

        //return typeConvert.short2byte(CRC);
    }

    public static boolean checkCrc16(byte[] src) {

        boolean flag = false;

        byte[] crc = getCrc16(src, src.length - 2);

        return crc[0] == src[src.length - 2] && crc[1] == src[src.length - 1];
    }
    
    public static byte GetSum_Byte(byte [] b,int Index,int Len)
    {
        byte Sum = 0;
        int i;
        for (i=0;i<Len;i++ )
        {
            Sum = (byte)(Sum+b[i+Index]);
        }
        return Sum;
    }

    public static boolean CheckSum_Byte(byte[] b, int Index, int Len, byte Sum) {
        byte Sum1 = 0;
        Sum1 = GetSum_Byte(b, Index, Len);
        if (Sum1 == Sum) {
            return true;
        } else {
            return false;
        }
    }
 /*   public static byte[] GetByteSum_Bytes(byte [] b)
    {
        byte [] Sum = new byte[1];
        Sum[0] = GetByteSum_Byte(b);
        return Sum;
    }*/
}
